<?php
declare(strict_types=1);
// hook common_start.php

function ConfigReload(): void
{
    // hook common_ConfigReload_brfore.php

    //加载配置文件

    $_ENV['conf'] = include _include(__SERDIR__ . __LV__ . '_config.php');
    $_ENV['database'] = include __SERDIR__ . __LV__ . '_database.php';
    $include_model_files = glob(__SYSDIR__ . '*.php');
    foreach ($include_model_files as $model_file) {
        $name = str_replace([__SYSDIR__, '.php'], '', $model_file);
        if ($name != 'Tables') {
            $_ENV['sys'][$name] = require_once _include($model_file);
        }
    }

    //这个暂时未使用
    /*
    $ipcity = __CONDIR__ . 'ip_city.csv';
    $cvs_file = fopen($ipcity, 'r'); //开始读取csv文件数据
    $i = 0;//记录cvs的行
    while ($file_data = fgetcsv($cvs_file)) {
        $i++;
        if ($file_data[0] != '') {
            $res = [];
            list($res['id'], $res['pid'], $res['name'], ,) = $file_data;
            $_ENV['ip_city'][$res['id']] = $res;
        }
    }
    fclose($cvs_file);
    */
    //$_ENV['VicWord'] =  new VicWord();
    //$_ENV['VicWord']->getWord('北京大学生喝进口红酒，在北京大学生活区喝进口红酒');
    //cachedDispatcher
    $_ENV['dispatcher'] = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
        // hook common_route_before.php

        $r->addRoute('GET', 'wechat.html', 'Wecaht/Index/Index');

        $r->addRoute('GET', 'support', 'Index/Support/Index');


        $r->addRoute('GET', 'question/add', 'Question/Index/Add');
        $r->addRoute('GET', 'question/{AskID:\d+}.html', 'Question/Index/Detail');
        $r->addRoute('GET', 'question/{page:\d+}', 'Question/Index/Index');
        $r->addRoute('GET', 'question/{name}[/{page:\d+}]', 'Question/Index/Index');
        $r->addRoute('GET', 'question/{name}/{name2}[/{page:\d+}]', 'Question/Index/Index');

        $r->addRoute('GET', 'promotion[/{page:\d+}]', 'Article/Index/Promotion');
        $r->addRoute('GET', 'promotion/{ArticleID:.+}.html', 'Article/Index/PromotionDetail');

        $r->addRoute('GET', 'news[/{page:\d+}]', 'Article/Index/Index');
        $r->addRoute('GET', 'news/{ArticleID:.+}.html', 'Article/Index/Detail');

        $r->addRoute('GET', 'terms.html', 'Pages/Index/Terms');
        $r->addRoute('GET', 'help[/{page:\d+}]', 'Pages/Index/Help');
        $r->addRoute('GET', 'help/{PageID:.+}.html', 'Pages/Index/Helpdetail');


        $r->addRoute('GET', 'docs', 'Pages/Index/Doc');
        $r->addRoute('GET', 'docs/{name}', 'Pages/Index/Docs');
        $r->addRoute('GET', 'docs/{name}/{title:.+}.html', 'Pages/Index/Docs');

        $r->addRoute('GET', 'fuwu', 'Products/Index/Fuwu');
        $r->addRoute('GET', 'fuwu/{name}.html', 'Products/Index/Fuwudetail');
        $r->addRoute('GET', 'products/{name}.html', 'Products/Index/Detail');
        $r->addRoute('GET', 'login.html', 'Users/Index/Login');

        $r->addRoute('GET', 'aigc/nav', 'Aigc/Index/Nav');
        $r->addRoute('GET', 'aigc/material[/{page:\d+}]', 'Aigc/Index/Page');
        $r->addRoute('GET', 'aigc/material/{PageID:.+}.html', 'Aigc/Index/Pagedetail');
        $r->addRoute('GET', 'aigc/tutorial[/{page:\d+}]', 'Aigc/Index/Page');
        $r->addRoute('GET', 'aigc/tutorial/{PageID:.+}.html', 'Aigc/Index/Pagedetail');
        // $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1');
        $TypeID = '{TypeID:onebpsearch|onebpdisplay|onebpadstrategydkx|onebpadstrategyruhui|onebpadstrategyliuzi|onebpadstrategyproductspeed|onebpadstrategycekuan|onebpadstrategyshangxin|onebpadstrategyyure|onebpadstrategywholeshop|onebpadstrategyfans|onebpadstrategycrowd|onebpitemmarketing|onebpmultiaim|onebpsite}';
        $TID = '{T:onebpsearch|onebpdisplay|onebpadstrategydkx|onebpadstrategyruhui|onebpadstrategyliuzi|onebpadstrategyproductspeed|onebpadstrategycekuan|onebpadstrategyshangxin|onebpadstrategyyure|onebpadstrategywholeshop|onebpadstrategyfans|onebpadstrategycrowd|onebpitemmarketing|onebpmultiaim|onebpsite}';
        //$TypeID ='{TypeID}';


        $r->addRoute('PUT', 'one/' . $TypeID . '/keyword/conf', 'One/Keyword/conf');
        $r->addRoute('PUT', 'one/' . $TypeID . '/wordpackage/conf', 'One/Wordpackage/conf');
        $r->addRoute('PUT', 'one/' . $TypeID . '/campaigngroup/conf', 'One/CampaignGroup/conf');
        $r->addRoute('PUT', 'one/' . $TypeID . '/campaign/conf', 'One/Campaign/conf');
        $r->addRoute('PUT', 'one/' . $TypeID . '/adgroup/conf', 'One/Adgroup/conf');
        $r->addRoute('PUT', 'one/' . $TypeID . '/adzone/conf', 'One/Adzone/conf');
        $r->addRoute('PUT', 'one/' . $TypeID . '/crowd/conf', 'One/Crowd/conf');
        $r->addRoute('PUT', 'one/' . $TypeID . '/creative/conf', 'One/Creative/conf');

        $r->addRoute('PUT', 'one/product/' . $TypeID . '/campaigngroup/conf', 'One/CampaignGroup/conf');
        $r->addRoute('PUT', 'one/product/' . $TypeID . '/campaign/conf', 'One/Campaign/conf');
        $r->addRoute('PUT', 'one/product/' . $TypeID . '/adgroup/conf', 'One/Adgroup/conf');
        $r->addRoute('PUT', 'one/product/' . $TypeID . '/adzone/conf', 'One/Adzone/conf');
        $r->addRoute('PUT', 'one/product/' . $TypeID . '/crowd/conf', 'One/Crowd/conf');
        $r->addRoute('PUT', 'one/product/' . $TypeID . '/creative/conf', 'One/Creative/conf');

        $r->addRoute('PUT', 'one/consumer/' . $TypeID . '/campaigngroup/conf', 'One/CampaignGroup/conf');
        $r->addRoute('PUT', 'one/consumer/' . $TypeID . '/campaign/conf', 'One/Campaign/conf');
        $r->addRoute('PUT', 'one/consumer/' . $TypeID . '/adgroup/conf', 'One/Adgroup/conf');
        $r->addRoute('PUT', 'one/consumer/' . $TypeID . '/adzone/conf', 'One/Adzone/conf');
        $r->addRoute('PUT', 'one/consumer/' . $TypeID . '/crowd/conf', 'One/Crowd/conf');
        $r->addRoute('PUT', 'one/consumer/' . $TypeID . '/creative/conf', 'One/Creative/conf');

        $r->addRoute('PUT', 'one/' . $TypeID . '/conf', 'One/Index/conf');
        $r->addRoute('PUT', 'one/{TypeID}/' . $TID . '/conf', 'One/Index/conf');

        /*
        question/q1713280979.htm
        $r->addRoute(['GET', 'POST'], 'qrcode/{url:.+}', 'index/index/qrcode');
        $r->addRoute(['GET', 'POST'], 'qrcodetxt/{txt:.+}/{key:\d+}', 'index/index/qrcodetxt');
        $r->addRoute(['GET', 'POST'], 'notify/{order_id:.+}', 'payment/index/index');
        $r->addRoute(['GET', 'POST'], 'notify_wechat/{order_id:.+}', 'payment/index/wechat');
        $r->addRoute(['GET', 'POST'], 'refund/{order_id:.+}', 'payment/refund/index');
        $r->addRoute(['GET', 'POST'], 'refund_wechat/{order_id:.+}', 'payment/refund/wechat');
        */
        // hook common_route_after.php
    });

    // hook common_ConfigReload_after.php
}


function IncludeFiles()
{

    // hook common_IncludeFiles_brfore.php


    // hook common_IncludeFiles_public_before.php


    $include_public_files = glob(__PUBDIR__ . '*.php');
    foreach ($include_public_files as $public_file) {
        require_once _include($public_file);
    }

    // hook common_IncludeFiles_model_before.php

    $is_load = [];
    $_ENV['_models'] = [];
    foreach ($_ENV['plugin_model_files'] as $k => $model_file) {
        if (file_exists($model_file)) {
            $is_load[$k] = $model_file;
            //require_once _include($model_file);
        }
    }

    $include_model_files = glob(__APPDIR__ . 'Model/*Model.php');
    foreach ($include_model_files as $model_file) {
        $name = str_replace([__APPDIR__ . "Model/", 'Model.php'], '', $model_file);
        if (!isset($is_load[$name]) && file_exists($model_file)) {
            $is_load[$name] = $model_file;
            //require_once _include($model_file);
        }
    }

    $include_model_files = glob(__APPDIR__ . 'Model/*/*Model.php');
    foreach ($include_model_files as $model_file) {
        $name = str_replace([dirname($model_file) . "/", 'Model.php'], '', $model_file);
        if (!isset($is_load[$name]) && file_exists($model_file)) {
            $is_load[$name] = $model_file;
            //require_once _include($model_file);
        }
    }
    $is_load_field = [];
    $fields = [];

    foreach ($_ENV['plugin_field_files'] as $k => $model_file) {
        if (file_exists($model_file)) {
            $is_load_field[$k] = 1;
            require_once _include($model_file);
            $fields[] = ['label' => $k, 'id' => constant("\\Field\\" . $k . 'Const::fields'), 'value' => constant("\\Field\\" . $k . 'Const::comment')];
        }
    }

    $include_model_files = glob(__APPDIR__ . 'Field/*.php');
    foreach ($include_model_files as $model_file) {
        $name = str_replace([__APPDIR__ . "Field/", 'Field.php', '.php'], '', $model_file);
        if (!isset($is_load_field[$name]) && file_exists($model_file)) {
            $is_load_field[$name] = 1;
            require_once _include($model_file);
            $fields[] = ['label' => $name, 'id' => constant("\\Field\\" . $name . 'Const::fields'), 'value' => constant("\\Field\\" . $name . 'Const::comment')];
        }
    }

    $include_model_files = glob(__APPDIR__ . 'Field/*/*.php');
    foreach ($include_model_files as $model_file) {
        $name = str_replace([dirname($model_file) . "/", 'Field.php', '.php'], '', $model_file);
        if (!isset($is_load_field[$name]) && file_exists($model_file)) {
            $is_load_field[$name] = 1;
            require_once _include($model_file);
            $fields[] = ['label' => $name, 'pk' => constant("\\Field\\" . $name . 'Const::pk'), 'id' => constant("\\Field\\" . $name . 'Const::fields'), 'value' => constant("\\Field\\" . $name . 'Const::comment')];
        }
    }
    $_ENV['_models_name'] = [];
    $is_load_dao = [];
    foreach ($_ENV['plugin_dao_files'] as $k => $model_file) {
        if (file_exists($model_file)) {
            $is_load_dao[$k] = $model_file;
            //require_once _include($model_file);
            $model = "\\Dao\\{$k}Dao";
            $_ENV['_models_name'][$k] = $model;
        }
    }

    $include_model_files = glob(__APPDIR__ . 'Dao/*Dao.php');
    foreach ($include_model_files as $model_file) {
        $name = str_replace([__APPDIR__ . "Dao/", 'Dao.php'], '', $model_file);
        if (!isset($is_load_dao[$name]) && file_exists($model_file)) {
            $is_load_dao[$name] = $model_file;
            //require_once _include($model_file);
            $model = "\\Dao\\{$name}Dao";
            $_ENV['_models_name'][$name] = $model;
        }
    }

    $include_model_files = glob(__APPDIR__ . 'Dao/*/*Dao.php');
    foreach ($include_model_files as $model_file) {
        $name = str_replace([dirname($model_file) . "/", 'Dao.php'], '', $model_file);
        if (!isset($is_load_dao[$name]) && file_exists($model_file)) {
            $is_load_dao[$name] = $model_file;
            //require_once _include($model_file);
            $model = "\\Dao\\{$name}Dao";
            $_ENV['_models_name'][$name] = $model;
        }
    }

    $libs = glob(__CFRDIR__ . 'Libs/*.php');
    foreach ($libs as $_file) {
        if ($_file == __CFRDIR__ . 'Libs/App.php') {
            continue;
        }
        include_once _include($_file);
    }

    require_once _include(__APPDIR__ . 'Task/Controller.php');
    require_once _include(__APPDIR__ . 'Controller/Controller.php');
    require_once _include(__APPDIR__ . 'Controller/Event.php');
    require_once _include(__APPDIR__ . 'Model.php');

    $controller_files = glob(__APPDIR__ . 'Controller/*.php');
    foreach ($controller_files as $controller_file) {
        if ($controller_file == __APPDIR__ . 'Controller/Controller.php' || $controller_file == __APPDIR__ . 'Controller/Event.php') {
            continue;
        }
        require_once _include($controller_file);
    }

    $controller_files = glob(__APPDIR__ . 'Task/*.php');
    foreach ($controller_files as $controller_file) {
        if ($controller_file == __APPDIR__ . 'Task/Controller.php') {
            continue;
        }
        require_once _include($controller_file);
    }


    foreach ($is_load as $name) {
        require_once _include($name);
    }

    foreach ($is_load_dao as $name) {
        require_once _include($name);
    }

    $_ENV['_models'] = [];
    foreach ($_ENV['_models_name'] as $name => $model) {
        $_ENV['_models'][$name] = new $model();
    }
    foreach ($_ENV['_models'] as $name => $model) {
        $model->auto_load();
    }

    // hook common_IncludeFiles_controller_before.php

    $is_load = [];
    foreach ($_ENV['plugin_top_controllers_file'] as $name => $controllers_file) {
        $is_load['\\' . $name] = 1;
        require_once _include($controllers_file);
    }


    foreach ($_ENV['plugin_controllers_files'] as $name => $controllers_file) {
        $is_load['\\' . $name] = 1;
        require_once _include($controllers_file);
    }

    foreach ($_ENV['plugin_top_task_controllers_file'] as $name => $controllers_file) {
        $is_load['\\' . $name] = 1;
        require_once _include($controllers_file);
    }
    foreach ($_ENV['plugin_task_controllers_files'] as $name => $controllers_file) {
        $is_load['\\' . $name] = 1;
        require_once _include($controllers_file);
    }

    foreach (scanPath(__APPDIR__ . "Controller/*/*") as $file) {
        $name = str_replace([__APPDIR__ . "Controller/", '.php'], '', $file);
        $name = '\\' . str_replace('/', '\\', $name);
        if (!isset($is_load[$name])) {
            $is_load[$name] = 1;
            require_once _include($file);
        }
    }

    foreach (scanPath(__APPDIR__ . "Task/*/*") as $file) {
        $name = str_replace([__APPDIR__ . "Task/", '.php'], '', $file);
        $name = '\\' . str_replace('/', '\\', $name);
        if (!isset($is_load[$name])) {
            $is_load[$name] = 1;
            require_once _include($file);
        }
    }
    $_class_name = [];
    try {
        $nodes = getMethodList();
        $method_arr = ['_get', '_post', '_patch', '_put', '_delete'];
        $_method_arr = ['_GET', '_POST', '_PATCH', '_PUT', '_DELETE'];
        $_method_arr_1 = ['_GET_', '_POST_', '_PATCH_', '_PUT_', '_DELETE_'];
        $_method_arr_2 = ['_get_', '_post_', '_patch_', '_put_', '_delete_'];

        $_controller = [];
        if ($nodes) {
            foreach ($nodes as $row) {
                if (!empty($row['action'])) {
                    $row['action'] = ucfirst(strtolower($row['action']));
                    $row['action'] = str_replace($method_arr, $_method_arr, $row['action']);
                    $row['action'] = str_replace($_method_arr_1, $_method_arr_2, $row['action']);
                    !empty($row['login']) && $row['auth'] = true;
                    $classname = strtoupper('\\' . $row['class_name']);
                    $_controller[$classname]["C"] = $row['class_name'];
                    $_controller[$classname][$row['action']] = ['auth' => $row['auth'], 'login' => $row['login']];
                }
                $_class_name[$row['class_name']] = 1;
            }


            if ($_ENV['bizan']->http_server->worker_id == 0) {
                /** @var  $SysMenu \Dao\SysMenuDao */
                $SysMenu = $_ENV['_models']["SysMenu"];
                $SysMenu->truncate();
                $insets = [];
                foreach ($nodes as $key => $node) {
                    $lastUnderscorePosition = strrpos($key, '_');
                    $method = '';
                    if ($lastUnderscorePosition !== false) {
                        $result = substr($key, $lastUnderscorePosition);
                        $method = xn_in_array($result, $method_arr) ? strtoupper(ltrim($result, '_')) : '';
                        $key = substr($key, 0, $lastUnderscorePosition);
                    }
                    //$_node = $SysMenu->readRow([SysMenuConst::Node => $key,SysMenuConst::Method => $method]);
                    $_key = explode('/', $key);
                    if (empty($node['namespace'])) {
                        unset($_key[count($_key) - 1]);
                        $node['namespace'] = implode('\\', $_key);
                    }
                    $data = new \Field\SysMenuColumns();
                    $data->ParentNode = $node['namespace'];
                    $data->Component = !empty($node['component']) ? $node['component'] : "vlist/index.vue";
                    $data->Name = !empty($node['title']) ? $node['title'] : $key;
                    $data->Hidden = !empty($node['hidden']) ? 1 : 0;
                    //$data->Fullpage=!empty($node['fullpage']) ? 1 : 0;
                    //$data->TypeId=!empty($node['typeid']) ? 1 : 0;
                    !empty($node['menu']) && $data->TypeId = 'menu';
                    $data->Icon = !empty($node['icon']) ? $node['icon'] : "el-icon-menu";
                    $data->Rank = !empty($node['rank']) ? $node['rank'] : 0;
                    $data->Login = !empty($node['login']) ? 1 : 0;
                    $data->Auth = !empty($node['auth']) ? 1 : 0;
                    $data->Menu = !empty($node['menu']) ? 1 : 0;
                    $data->Active = !empty($node['active']) ? 1 : 0;
                    $data->Node = $key;
                    $data->Method = $method;
                    $insets[] = $data->toArray();
                }
                $SysMenu->insertAll($insets);
            }
        }
        $_ENV['_controller_name'] = $_controller;
    } catch (ReflectionException $e) {

    }


    try {
        $nodes = getTaskMethodList();
        $_task_controller = [];
        if ($nodes) {
            foreach ($nodes as $row) {
                if (!empty($row['action'])) {
                    $row['action'] = ucfirst($row['action']);
                    $_task_controller['\\' . $row['class_name']][$row['action']] = 1;
                }
                $_class_name[$row['class_name']] = 1;
            }
        }
        $_ENV['_taks_controller_name'] = $_task_controller;
    } catch (ReflectionException $e) {

    }

    $_ENV['fields'] = $fields;
    $_ENV['_class_name'] = array_keys($_class_name);

    require_once _include(__CFRDIR__ . 'Libs/App.php');

    // hook common_IncludeFiles_after.php
}

// hook common_end.php
?>